import {
  Card,
  Breadcrumb,
  Radio,
  Button,
  Form,
  Select,
  Input,
  message,
  Upload,
} from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import './index.scss'
import { useEffect, useSearchParams, useRef, useState } from 'react'
import { useStore } from '../../store'
import { http } from '../../utils/http'
import { Link, useNavigate } from 'react-router-dom'
// 富文本
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'

const { Option } = Select

function Publish() {
  const { channelStore } = useStore()

  // 用useRef声明一个图片暂存仓库，用来切换radio时储存
  const saveImgList = useRef()

  // rodio切换图片 判断上传是否展示
  const [imgCount, setImageCount] = useState(1)
  const radioChange = (e) => {
    setImageCount(e.target.value)

    // 从仓库里取对应的图片数量 改变fileList值
    // 这里会有个问题：useState不是实时更新的。解决办法：1.单图时写多图的逻辑，多图写单独的逻辑，对调；
    // 2. 用e.target.value替换imgCount
    const currentVal = e.target.value

    // 无图
    if (currentVal === 0) {
      return false
    }
    // 单图
    if (currentVal === 1) {
      const img = saveImgList.current ? saveImgList.current[0] : []
      setFileList([img])
      // 多图
    } else if (currentVal === 3) {
      const img = saveImgList.current
      setFileList([img])
    }
  }

  // 存放上传图片的列表
  const [fileList, setFileList] = useState([])
  const handleChange = (info) => {
    setFileList(info.fileList)
    console.log(fileList)

    // 存入ref中
    saveImgList.current = fileList
  }

  const onFinish = async (values) => {
    console.log(fileList)
    const { channel_id, content, title, type } = values
    // 判断type fileList 是匹配的才能正常提交
    const params = {
      channel_id,
      content,
      title,
      type,
      cover: {
        type: type,
        // 注意
        images: fileList.map(item => item.url)
      },
    }
    console.log(params)
    if(id) {
        await http.put(`/mp/articles/${id}?draft=false`, params)
    } else {
        await http.post('/mp/articles?draft=false', params)
    }
  }

  // 编辑功能
  // 路由参数id
  //   const [params] = useSearchParams() // 报错原因不明
  //   const id = params.get('id')
  // 改用如下：
  const [id, setId] = useState('')

  // 编辑数据展示：id调接口。 1.表单回填；2.暂存列表；3.Upload组件fileList
  // form: 需在From组件上定义
  const [form] = Form.useForm() // Form.useForm对表单数据域进行交互，只作用于函数组件
  useEffect(() => {
    // 放外面会拿不到id
    if (window.location.search) {
      setId(window.location.search.substring(4))
    }

    const loadDetail = async () => {
      const res = await http.get(`/mp/articles/${id}`)
      const data = res.data
      console.log(data)
      // 表单回填
      form.setFieldsValue({ ...data, type: data.cover.type })
      // Upload组件fileList 注意格式
      const formatImgList = data.cover.images.map((url) => ({ url }))
      setFileList(formatImgList)
      // 暂存列表
      saveImgList.current = formatImgList
      // 图片type
      setImageCount(data.cover.type)
    }
    // 必须是编辑状态 才可以发送请求
    if (id) {
      loadDetail()
    }
  }, [id, form])

  return (
    <div className="Publish">
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          initialValues={{ type: 1, content: '' }}
          className="Publishfrom"
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select style={{ width: 400 }} placeholder="请选择文章频道">
              {channelStore.channelList.map((item) => {
                return (
                  <Option value={item.name} key={item.id}>
                    {item.name}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={radioChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgCount > 0 && (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                fileList={fileList}
                onChange={handleChange}
                multiple={imgCount > 1}
                maxCount={imgCount}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill theme="snow" />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Button size="large" type="primary" htmlType="submit">
              {id ? '更新' : '发布'}文章
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish
